import axios from "axios";

const BASE_URL = '/api'

axios.interceptors.response.use(response => {
    if (response.data.code === 401) {
        window.localStorage.removeItem('token')
        window.localStorage.removeItem('user')
        window.location = '/403'
    }
    return response;
}, error => {
    if (error.response.status === 401) {
        window.localStorage.removeItem('token')
        window.localStorage.removeItem('user')
        window.location = '/403'
    }
    return Promise.reject(error)
})

export const apiRequest = (config) => {
    // 自动携带认证
    if (!config.headers) {
        config["headers"] = {}
    }
    config["headers"]["Authorization"] = "Bearer " + window.localStorage.getItem('token')
    // 请求处理
    return new Promise((resolve, reject) => {
        axios.request(config).then(res => {
            resolve(res)
        }).catch(e => {
            if (e.code === 401) {
            }
            reject(e.code)
        })
    })
}

export const apiPost = (url, data) => {
    return apiRequest({
        url: BASE_URL + url,
        method: 'POST',
        data
    })
}

export const apiGet = (url) => {
    return apiRequest({
        url: BASE_URL + url,
        method: 'GET'
    })
}

export const apiPut = (url, data) => {
    return apiRequest({
        url: BASE_URL + url,
        method: 'PUT',
        data
    })
}

export const apiDelete = (url) => {
    return apiRequest({
        url: BASE_URL + url,
        method: 'DELETE'
    })
}